package service

import (
	"bytes"
	"dks-goweb/model"
	"dks-goweb/utils"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
)

// 获取 accessToken
func GetAccessToken(cIdentity string) (string, error) {
	// 发送请求获取 accessToken
	url := fmt.Sprintf("https://cloud-api.aiotzy.com/api/auth/oauth/token?cIdentity=%s&grant_type=device&client_id=zmp-h5&client_secret=VIlA38m0G2YwGagS&path=https%%3A%%2F%%2Fcloud.aiotzy.com", cIdentity)

	body, err := utils.PostRequest(url, nil)

	// 解析响应体
	var tokenResponse model.TokenResponse
	err = json.Unmarshal(body, &tokenResponse)
	if err != nil {

		return "", err
	}

	// 组合 Bearer token
	accessToken := tokenResponse.Data.TokenHead + tokenResponse.Data.AccessToken
	return accessToken, nil
}

func statusConverter(status string) string {
	switch status {
	case "0":
		return "待使用"
	case "1":
		return "生效中"
	case "2":
		return "已失效"
	case "3":
		return "已过期"
	case "4":
		return "已退款"
	default:
		return status
	}
}

// 使用 accessToken 请求数据
func QueryPoolPackageInfo(accessToken string, terminalId string) (model.SimplifiedResponse, error) {
	// 构造请求体
	requestBody, err := json.Marshal(model.PackageRequest{TerminalId: terminalId})
	if err != nil {
		return model.SimplifiedResponse{}, err
	}

	// 构造请求
	req, err := http.NewRequest("POST", "https://cloud-api.aiotzy.com/api/meter/h5/meterBaseMeter/packageInfo", bytes.NewBuffer(requestBody))
	if err != nil {
		return model.SimplifiedResponse{Code: "500", Msg: "发送请求失败", Success: false, CardDealer: "未知"}, err
	}

	// 设置请求头
	req.Header.Set("Authorization", accessToken)
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return model.SimplifiedResponse{Code: "500", Msg: err.Error(), Success: false, CardDealer: "未知"}, err
	}
	defer resp.Body.Close()

	// 读取响应体
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return model.SimplifiedResponse{Code: "500", Msg: err.Error(), Success: false, CardDealer: "未知"}, err
	}

	// 解析响应体
	var packageResponse model.PackageResponse
	err = json.Unmarshal(body, &packageResponse)
	if err != nil {
		return model.SimplifiedResponse{Code: "500", Msg: "卡号不存在或被注销", Success: false, CardDealer: "未知"}, nil
	}

	// 将响应体转换为简化后的格式
	simplifiedData := make(map[string][]model.SimplifiedPackage)
	for key, packages := range packageResponse.Data {
		var simplifiedPackages []model.SimplifiedPackage
		for _, pkg := range packages {
			if len(pkg.MeterUsageInfo) > 0 {
				usageInfo := pkg.MeterUsageInfo[0]
				simplifiedPackages = append(simplifiedPackages, model.SimplifiedPackage{
					PackageName:    pkg.PackageName,
					Status:         statusConverter(pkg.Status),
					EffectiveDate:  pkg.EffectiveDate,
					ExpirationDate: pkg.ExpirationDate,
					Total:          usageInfo.Total,
					Usage:          usageInfo.Usage,
				})

			}
		}
		simplifiedData[key] = simplifiedPackages
	}

	// 构造简化后的响应体
	simplifiedResponse := model.SimplifiedResponse{
		Code:       packageResponse.Code,
		Msg:        packageResponse.Msg,
		Data:       simplifiedData,
		Success:    packageResponse.Success,
		CardDealer: "网亿流量池",
	}

	if strings.Contains(simplifiedResponse.Msg, "登录过期") {
		simplifiedResponse.CardDealer = "未知"
	} else if simplifiedResponse.Msg == "" {
		simplifiedResponse.CardDealer = "未知"
	} else {
		simplifiedResponse.CardDealer = "网亿流量池"
	}

	return simplifiedResponse, nil
}
